package com.coderman.infosys.auth.domain.bo.user;

import java.util.*;
import java.util.stream.Collectors;

import com.coderman.infosys.auth.domain.bo.role.RoleBO;
import com.coderman.infosys.auth.domain.bo.role.RoleGroupBO;

import com.coderman.infosys.auth.domain.support.bo.UserBO;
import com.coderman.infosys.plat.auth.common.bo.BaseBO;
import com.coderman.infosys.plat.auth.common.enums.StatusEnum;
import lombok.Data;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;

/**
* @Description:用户组类---这里是聚合根？
 *
* @Author:shenshuai
* @CreateTime:2022-01-02 15:27:38
* @version v1.0
*/
@Data
@ToString
public class UserGroupBO extends BaseBO {

   public UserGroupBO(){}

   public UserGroupBO(String userGroupCode){
      this.groupCode = userGroupCode;
   }

   /** 主键ID **/
   private Long id;

   /** 组名 **/
   private String groupName;

   /** 组编码 **/
   private String groupCode;

   /** 组内用户列表 **/
   private List<UserBO> userBOList;

   /** 用户组状态 **/
   private Integer status;

   /** 用户组对应的角色列表 **/
   private List<RoleBO> roleList = new ArrayList<>();

   /** 用户组对应角色组列表 **/
   private List<RoleGroupBO> roleGroupList = new ArrayList<>();

   /**
    * 根据实体标示构建UserGroupBO对象
    * @param userGroupCode
    * @return
    */
   public static UserGroupBO ofIdentifer(String userGroupCode){
      return new UserGroupBO(userGroupCode);
   }

   /**
    *
    * @Description:判断角色是否在该用户组
    * @return boolean
    */
   public boolean containsRole(String roleCode){
      Optional<RoleBO> roleBOOptional = this.roleList.stream().filter(roleBO -> Objects.equals(roleBO,roleBO.getRoleCode())).findFirst();
      return roleBOOptional.isPresent();
   }
   /**
    *
    * @Description:判断用户是否在该用户组
    * @return boolean
    */
   public boolean containsUser(Long userId){
      Optional<UserBO> roleBOOptional = this.userBOList.stream().filter(userBO -> Objects.equals(userId,userBO.getUserId())).findFirst();
      return roleBOOptional.isPresent();
   }
   /**
    *
    * @Description:将用户从用户组中删
    * @return 用户列表字符串
    */
   public String deleteUser(Long userId){
      Set<Long> userIdList = this.userBOList.stream().map(UserBO::getUserId).collect(Collectors.toSet());
      userIdList.remove(userId);
      return buildUserList();
   }

   /**
    * 构建用户组字符串
    * @return
    */
   public String buildUserList(){
      if(this.userBOList == null || this.userBOList.isEmpty()){
         return "";
      }
      List<Long> userIdList = this.userBOList.stream().map(UserBO::getUserId).collect(Collectors.toList());
      return StringUtils.join(userIdList,",");
   }


   public void disable(){
      this.status = StatusEnum.DISABLE.getStatus();
   }

   public void enable(){
      this.status = StatusEnum.ENABLE.getStatus();
   }

}